// pages/student/video-player/video-player.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    courseId: null,
    courseInfo: {},
    currentVideo: {},
    videoList: [],
    currentVideoIndex: 0,
    liked: false,
    showNotesModal: false,
    noteContent: '',
    videoContext: null,
    playbackPosition: 0,
    isPlaying: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('视频播放器页面加载，参数:', options);
    
    const courseId = options.courseId;
    if (courseId) {
      this.setData({
        courseId: parseInt(courseId)
      });
      console.log('设置课程ID:', courseId);
      this.loadCourseData();
    } else {
      console.log('没有课程ID，创建测试环境');
      // 如果没有课程ID，创建一个测试环境
      this.createTestEnvironment();
    }
  },

  // 创建测试环境
  createTestEnvironment() {
    const testCourse = {
      id: 999,
      title: "视频播放测试课程",
      teacher: "霍丙乾bennyhuo",
      totalVideos: 3,
      watchedVideos: 0,
      cover: "../../images/avatar-default.svg",
      description: "这是一个测试课程，包含三个视频"
    };

    // 保存测试课程到本地存储
    let courses = wx.getStorageSync('studentCourses') || [];
    const existingCourseIndex = courses.findIndex(c => c.id === 999);
    if (existingCourseIndex !== -1) {
      courses[existingCourseIndex] = testCourse;
    } else {
      courses.push(testCourse);
    }
    wx.setStorageSync('studentCourses', courses);

    this.setData({
      courseId: 999,
      courseInfo: testCourse
    });

    // 生成包含测试视频的视频列表
    const videoList = this.generateVideoList(testCourse);
    const currentVideo = videoList[0];

    this.setData({
      videoList: videoList,
      currentVideo: currentVideo,
      currentVideoIndex: 0
    });

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: testCourse.title
    });

    wx.showToast({
      title: '测试环境已加载',
      icon: 'success'
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    // 创建视频上下文
    this.videoContext = wx.createVideoContext('videoPlayer');
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 恢复播放进度
    this.restorePlaybackPosition();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    // 保存播放进度
    this.savePlaybackPosition();
    // 暂停视频播放
    if (this.videoContext) {
      this.videoContext.pause();
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 保存播放进度和学习记录
    this.savePlaybackPosition();
    this.updateLearningProgress();
  },

  // 加载课程数据
  loadCourseData() {
    console.log('开始加载课程数据，课程ID:', this.data.courseId);
    
    // 从本地存储或服务器获取课程数据
    const courses = wx.getStorageSync('studentCourses') || [];
    console.log('从本地存储获取的课程数据:', courses);
    
    let course = courses.find(c => c.id === this.data.courseId);
    console.log('找到的课程:', course);

    // 如果找不到课程数据，使用测试数据
    if (!course) {
      console.log('课程不存在，使用测试数据');
      course = {
        id: this.data.courseId,
        title: "视频播放测试课程",
        teacher: "霍丙乾bennyhuo",
        totalVideos: 3,
        watchedVideos: 0,
        cover: "../../images/avatar-default.svg",
        description: "这是一个测试课程，包含三个视频"
      };
    }

    // 生成视频列表数据
    const videoList = this.generateVideoList(course);
    const currentVideo = videoList[0];
    
    console.log('生成的视频列表:', videoList);
    console.log('当前视频:', currentVideo);

    this.setData({
      courseInfo: course,
      videoList: videoList,
      currentVideo: currentVideo,
      currentVideoIndex: 0
    });

    // 设置页面标题
    wx.setNavigationBarTitle({
      title: course.title
    });

    // 加载播放记录
    this.loadPlaybackRecord();
  },

  // 生成视频列表（模拟数据）
  generateVideoList(course) {
    const videos = [];
    
    // 使用用户提供的三个视频URL
    const videoUrls = [
      "https://jieruoda.cn/video/huo-2.2/1.mp4",
      "https://jieruoda.cn/video/huo-2.2/2.mp4", 
      "https://jieruoda.cn/video/huo-2.2/3.mp4"
    ];
    
    const videoTitles = [
      "第1课：context parameter 和 receiver 有啥区别？",
      "第2课：一项上下文相关的语法解析优化",
      "第3课：构造器参数上的注解到底是标注给谁的？"
    ];
    
    const videoDurations = [
      "4分钟",
      "5分钟", 
      "4分钟"
    ];
    
    // 创建三个视频
    for (let i = 0; i < 3; i++) {
      videos.push({
        id: i + 1,
        title: videoTitles[i],
        duration: videoDurations[i],
        url: videoUrls[i],
        cover: course.cover || "../../images/avatar-default.svg",
        watched: i < course.watchedVideos,
        locked: false
      });
    }
    
    return videos;
  },

  // 选择视频
  selectVideo(e) {
    const videoId = e.currentTarget.dataset.id;
    const videoIndex = this.data.videoList.findIndex(v => v.id === videoId);

    if (videoIndex !== -1) {
      const video = this.data.videoList[videoIndex];

      // 检查视频是否锁定
      if (video.locked) {
        wx.showToast({
          title: '该视频暂未解锁',
          icon: 'none'
        });
        return;
      }

      this.setData({
        currentVideo: video,
        currentVideoIndex: videoIndex
      });

      // 切换视频时保存上一个视频的播放进度
      this.savePlaybackPosition();
    }
  },

  // 播放上一个视频
  playPreviousVideo() {
    const prevIndex = this.data.currentVideoIndex - 1;
    if (prevIndex >= 0) {
      const prevVideo = this.data.videoList[prevIndex];
      this.setData({
        currentVideo: prevVideo,
        currentVideoIndex: prevIndex
      });
      this.savePlaybackPosition();
    } else {
      wx.showToast({
        title: '已经是第一集了',
        icon: 'none'
      });
    }
  },

  // 播放下一个视频
  playNextVideo() {
    const nextIndex = this.data.currentVideoIndex + 1;
    if (nextIndex < this.data.videoList.length) {
      const nextVideo = this.data.videoList[nextIndex];

      if (nextVideo.locked) {
        wx.showToast({
          title: '该视频暂未解锁',
          icon: 'none'
        });
        return;
      }

      this.setData({
        currentVideo: nextVideo,
        currentVideoIndex: nextIndex
      });
      this.savePlaybackPosition();
    } else {
      wx.showToast({
        title: '已经是最后一集了',
        icon: 'none'
      });
    }
  },

  // 视频播放事件
  onVideoPlay(e) {
    this.setData({
      isPlaying: true
    });
    console.log('视频开始播放');
  },

  // 视频暂停事件
  onVideoPause(e) {
    this.setData({
      isPlaying: false
    });
    console.log('视频暂停');
  },

  // 视频结束事件
  onVideoEnd(e) {
    this.setData({
      isPlaying: false
    });

    // 标记当前视频为已观看
    this.markVideoAsWatched();

    // 自动播放下一个视频
    setTimeout(() => {
      this.playNextVideo();
    }, 1000);
  },

  // 视频时间更新事件
  onVideoTimeUpdate(e) {
    const currentTime = e.detail.currentTime;
    this.setData({
      playbackPosition: currentTime
    });
  },

  // 视频错误事件
  onVideoError(e) {
    console.error('视频播放错误:', e);
    wx.showToast({
      title: '视频播放失败',
      icon: 'error'
    });
  },

  // 标记视频为已观看
  markVideoAsWatched() {
    const videoList = this.data.videoList;
    const currentIndex = this.data.currentVideoIndex;

    if (videoList[currentIndex]) {
      videoList[currentIndex].watched = true;
      this.setData({
        videoList: videoList
      });

      // 更新课程进度
      this.updateCourseProgress();
    }
  },

  // 更新课程进度
  updateCourseProgress() {
    const watchedCount = this.data.videoList.filter(v => v.watched).length;
    const totalCount = this.data.videoList.length;
    const progress = Math.round((watchedCount / totalCount) * 100);

    // 更新本地存储中的课程进度
    let courses = wx.getStorageSync('studentCourses') || [];
    const courseIndex = courses.findIndex(c => c.id === this.data.courseId);

    if (courseIndex !== -1) {
      courses[courseIndex].watchedVideos = watchedCount;
      courses[courseIndex].progress = progress;
      wx.setStorageSync('studentCourses', courses);
    }
  },

  // 保存播放进度
  savePlaybackPosition() {
    const key = `playback_${this.data.courseId}_${this.data.currentVideo.id}`;
    wx.setStorageSync(key, {
      position: this.data.playbackPosition,
      timestamp: Date.now()
    });
  },

  // 恢复播放进度
  restorePlaybackPosition() {
    const key = `playback_${this.data.courseId}_${this.data.currentVideo.id}`;
    const record = wx.getStorageSync(key);

    if (record && record.position > 0) {
      // 如果有播放记录，询问用户是否继续播放
      wx.showModal({
        title: '继续播放',
        content: `检测到您上次观看到${Math.floor(record.position / 60)}分${Math.floor(record.position % 60)}秒，是否继续播放？`,
        success: (res) => {
          if (res.confirm && this.videoContext) {
            this.videoContext.seek(record.position);
          }
        }
      });
    }
  },

  // 加载播放记录
  loadPlaybackRecord() {
    // 加载收藏状态
    const likedCourses = wx.getStorageSync('likedCourses') || [];
    const liked = likedCourses.includes(this.data.courseId);
    this.setData({ liked });

    // 加载笔记内容
    const noteKey = `note_${this.data.courseId}_${this.data.currentVideo.id}`;
    const noteContent = wx.getStorageSync(noteKey) || '';
    this.setData({ noteContent });
  },

  // 更新学习进度
  updateLearningProgress() {
    const progressKey = `learning_progress_${this.data.courseId}`;
    const progress = {
      courseId: this.data.courseId,
      lastVideoId: this.data.currentVideo.id,
      lastPlaybackPosition: this.data.playbackPosition,
      lastWatchTime: Date.now(),
      watchedVideos: this.data.videoList.filter(v => v.watched).length
    };
    wx.setStorageSync(progressKey, progress);
  },

  // 收藏/取消收藏
  toggleLike() {
    const liked = !this.data.liked;
    this.setData({ liked });

    let likedCourses = wx.getStorageSync('likedCourses') || [];
    if (liked) {
      likedCourses.push(this.data.courseId);
    } else {
      likedCourses = likedCourses.filter(id => id !== this.data.courseId);
    }
    wx.setStorageSync('likedCourses', likedCourses);

    wx.showToast({
      title: liked ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 分享视频
  shareVideo() {
    // 实现分享功能
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 显示笔记弹窗
  showNotes() {
    this.setData({
      showNotesModal: true
    });
  },

  // 隐藏笔记弹窗
  hideNotes() {
    this.setData({
      showNotesModal: false
    });
  },

  // 笔记输入
  onNoteInput(e) {
    this.setData({
      noteContent: e.detail.value
    });
  },

  // 保存笔记
  saveNote() {
    const noteKey = `note_${this.data.courseId}_${this.data.currentVideo.id}`;
    wx.setStorageSync(noteKey, this.data.noteContent);

    this.setData({
      showNotesModal: false
    });

    wx.showToast({
      title: '笔记保存成功',
      icon: 'success'
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.loadCourseData();
    wx.stopPullDownRefresh();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: `正在学习：${this.data.courseInfo.title}`,
      path: `/pages/student/video-player/video-player?courseId=${this.data.courseId}`,
      imageUrl: this.data.courseInfo.cover
    };
  }
});